<?php

/** 
 * Libraries 
 * 
 * PHP SiteTalk Framework. 
 * 
 * @package     Libraries 
 * @version     1.1 
 * @author     Developer Nguyen Khanh Thanh
 * @license     SiteTalk v1 
 * @link 
 * 
 */

class Tool {
	/**
	 * Validate whether an email is valid or not.
	 * @param String $email
	 * @throws Exception: if the email is invalid
	 */
	static public function validateEmail($email) 
	{
		//invalid email if empty
		if(Tool::isEmpty($email)) 
		{
			throw new Exception("Email Cant be Empty");
		}
			
		//TODO: if email in invalid format throw exception("Invalid Email Format")
		$validate_email = preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email);
		if(!$validate_email) 
		{
			throw new Exception("Invalid Email Format");
		}	
		return $validate_email;
	}
	
	/**
	 * Enter description here ...
	 * @param String $password
	 * @return true if valid, otherwise throw exception
	 * @throws Exception
	 */
	static public function validatePassword($password) 
	{
		//Password should be minimum 8 characters long and contains at least 1 numeric number
		$validate_password = preg_match("/^(?=.*\d).{8,}$/", $password);
			
		if(!$validate_password){
			throw new Exception("Invalid Password Format");
		}
		return $validate_password;
	}
	
	/**
	 * check whether the input is empty or not.
	 * for normal object, check whether it is null, 
	 * for string object, check whether it is empty string or null
	 * @param Object $data
	 */
	static public function isEmpty($data) {
		if(isset($data)) {
			//TODO: check whether the input is empty or not
			if(Empty($data))
			{
				return true;
			}
			
			//for normal object, check whether it is null
			else if(is_null($data))
			{
				return true;
			}
			//for string object, check whether it is empty string (after trim) or null
			else if (is_array($data))
			{
				if($data == null) 
					return true;
				else 
					return false;
			}
			else if(is_object($data))
			{
				$a = (array)$data;
				if($a == null) 
					return true;
				else 
					return false;
			}
			
			else if(trim($data) == "" || trim($data) == null)
			{
				return true;
			}
			else 
			{
				return false;
			}
		} 
		else 
		{
			return true;
		}
	}
	
	/**
	 * return current server date in format: yyyyMMdd
	 */
	static public function getToday() {
		return date("Ymd");
	}
	
	/**
	 * return current server timestamp in php timestamp format
	 */
	static public function getCurrentPHPTimeStamp() {
		$date = new DateTime();
		return $date->getTimestamp();
	}
	
	/**
	 * return a string representative of php timestamp, in format of yyyyMMddHHmmss
	 * @param long $phpTimeStamp
	 */
	static public function convertTSyyyyMMddHHmmss($phpTimeStamp) {
		$datetime = date("YmdHis", $phpTimeStamp);
		return $datetime;
	}
	static public function ddMMyyyy($str) {
		$ts = strtotime($str);
		return  date('d-m-Y', $ts);
	}
	static public function splitString2Array($str) {
		$arr = explode(",", $str);
		return $arr;
	}
	static public function curPageURL() {
		 $pageURL = 'http';
		 if (!empty($_SERVER['HTTPS'])) {if($_SERVER['HTTPS'] == 'on'){$pageURL .= "s";}} 
		 $pageURL .= "://";
		 if ($_SERVER["SERVER_PORT"] != "80") {
		  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
		 } else {
		  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
		 }
		 return $pageURL;
	}
	
	static public function encode($string,$key) {
	  $key = sha1($key);
	  $strLen = strlen($string);
	  $keyLen = strlen($key);
	  $hash = '';
 	  $y = 0;
	  for ($x = 0; $x < $strLen; $x++) {
	    $ordStr = ord(substr($string,$x,1));
	    if ($y == $keyLen) { $y = 0; }
	    $ordKey = ord(substr($key,$y,1));
	    $y++;
	    $hash .= strrev(base_convert(dechex($ordStr + $ordKey),16,36));
	  }
	  return $hash;
	}
	
	static public function decode($string,$key) {
	  $key = sha1($key);
	  $strLen = strlen($string);
	  $keyLen = strlen($key);
	  $hash = '';
  	  $y = 0;
	  for ($x = 0; $x < $strLen; $x+=2) {
	    $ordStr = hexdec(base_convert(strrev(substr($string,$x,2)),36,16));
	    if ($y == $keyLen) { $y = 0; }
	    $ordKey = ord(substr($key,$y,1));
	    $y++;
	    $hash .= chr($ordStr - $ordKey);
	  }
	  return $hash;
	}
	
	static public function xssAndSQLInjectionClean($data)
	{
	// Fix &entity\n;
	$data = str_replace(array('&amp;','&lt;','&gt;'), array('&amp;amp;','&amp;lt;','&amp;gt;'), $data);
	$data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
	$data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
	$data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');
	
	// Remove any attribute starting with "on" or xmlns
	$data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);
	
	// Remove javascript: and vbscript: protocols
	$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
	$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
	$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);
	
	// Only works in IE: <span style="width: expression(alert('Ping!'));"></span>
	$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
	$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
	$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);
	
	// Remove namespaced elements (we do not need them)
	$data = preg_replace('#</*\w+:\w[^>]*+>#i', '', $data);
	
	do
	{
	        // Remove really unwanted tags
	        $old_data = $data;
	        $data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
	}
	while ($old_data !== $data);
	if(!get_magic_quotes_gpc()) {
    	$data = addslashes($data);
    }
	$data = strip_tags(htmlspecialchars($data));
	//return $str;
	// we are done...
	return $data;
	}
	
	static public function DateDiff($date, $numDate)
	{
		$dateNow = time();
		$convertDate = new DateTime($date);
		$dateTime = $convertDate->getTimestamp();
		$dateDiff = $dateNow - $dateTime;
		$rs = $dateDiff/3600/24;
		if($rs <= $numDate)
		{
			return true;
		}
		else 
			return false;
		
	}
	
	static public function getAllMethodNameOfClass($className) {
		$classname = get_class($className);
		$methodnames = get_class_methods($classname);
		$arrayName = array();
		foreach ($methodnames as $methodname){
			array_push($arrayName, $methodname);
		}
		return $arrayName;
	}
	
	static public function checkMethodNameExistInClass($className, $methodName) {
		$arrayName = Tool::getAllMethodNameOfClass($className);
		if(in_array($methodName, $arrayName))
		{
			return true;
		}
		else 
			return false;
	}
	
	static function md5_base64($data) {
	    return base64_encode(pack('H*',md5($data)));
	}
	
	function full_url()
	{
    $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
    $protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
    $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
    return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
	}
	
	function unixToMySQL($timestamp)
	{
	    return date('Y-m-d H:i:s', $timestamp);
	}
	
	static function convert24hTo12h($time)
	{
		return date('g:i a', strtotime($time));
	}
	
	static function convert12hTo24h($time)
	{
		return date('H:i', strtotime($time));;
	}
	
}

?>
